<template>
  <view class="news">
    <view class="news-tab u-font-30 u-text-center u-flex">
      <view @click="tabActive = index" v-for="(item, index) in tabList" :key="index" :class="{active: tabActive == index}" class="item u-flex-1">{{item.name}}</view>
    </view>
    <template v-if="!tabActive">
      <view class="news-list u-p-20">
        <view @click="navLink(item)" v-for="(item, index) in newsList" :key="index" class="item u-p-10">
          <view class="info u-flex">
            <view @click.stop="linkDetail(item)">
              <u-image :src="item.avatar" mode="widthFix" width="60" shape="circle"></u-image>
            </view>
            <view class="name u-flex-1 u-m-l-20">{{item.nickname || ""}}</view>
            <u-tag v-if="!item.is_k" text="未读" bg-color="#f24646" color="#fff" border-color="#fff" />
            <u-tag v-else text="已读" bg-color="#4cd964" color="#fff" border-color="#fff" />
          </view>
          <view :class="{active: item.type == 5}" class="content">{{item.content || ""}}</view>
          <view class="time u-font-26 u-text-right">{{item.createtime || ""}}</view>
        </view>
      </view>
      <u-loadmore :status="status" class="u-p-20" />
      <u-back-top :scroll-top="scrollTop" :bottom="bottom" :right="20" :icon-style="iconStyle" :custom-style="customStyle"></u-back-top>
    </template>
    <template v-else>
      <view v-if="userAddConversationList.length" class="news-tim u-p-20">
        <view @click="toRoom(item)" v-for="(item, index) in userAddConversationList" :key="index" class="item u-p-10 u-flex u-col-top">
          <u-image :src="item.user.img" mode="aspectFill" width="100" height="100" shape="circle"></u-image>
          <view class="info u-flex-1 u-m-l-20 u-m-r-20 u-flex-col u-row-between">
            <view class="name u-m-b-20">{{item.user.user || ""}}</view>
            <u-parse @imgtap="imgtap($event, item)" :html="item.conversation.lastMessage.messageForShow"></u-parse>
          </view>
          <view v-if="item.conversation.unreadCount" class="msg">{{item.conversation.unreadCount || ""}}</view>
        </view>
      </view>
      <view v-else class="news-box u-p-20">暂无聊天记录，请选择好友进行聊天</view>
    </template>
    <u-popup v-model="popupShow" mode="center" border-radius="10" :closeable="true" width="90%">
      <view class="popup u-p-30">
        <view class="popup-title u-font-32 u-text-center">群聊二维码</view>
        <view class="popup-image u-m-t-20">
          <u-image :src="qrCode" mode="widthFix" width="100%" border-radius="10"></u-image>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      tabList: [{ name: "平台消息通知" }, { name: "互动消息通知" }],
      tabActive: 0,
      newsList: [],
      status: "nomore",
      scrollTop: 0,
      bottom: 100,
      iconStyle: {
        fontSize: "40rpx",
        color: "#fff",
      },
      customStyle: {
        backgroundColor: "rgba(0, 0, 0, .6)",
      },
      popupShow: false,
      qrCode: "",
      page: 1,
      pagesize: 10,
      userAddConversationList: [],
    };
  },
  computed: {
    ...mapState(["vuex_user_id", "vuex_identity", "vuex_user_info"]),
    ...mapState({
      isLogin: (state) => state.isLogin,
      isSDKReady: (state) => state.isSDKReady,
      conversationList: (state) => state.conversationList,
    }),
  },
  watch: {
    isSDKReady(val) {
      if (val) this.getConversationList();
    },
    conversationList(val) {
      this.getUserInfo(val);
    },
  },
  onShow() {
    if (!this.vuex_user_id)
      return uni.navigateTo({ url: "/pages/subpackages/mine/login/login" });
    this.page = 1;
    this.newsList = [];
    this.getNewsList();
    if (this.isSDKReady) this.getConversationList();
  },
  methods: {
    // 消息列表
    getNewsList() {
      let data = {
        user_id: this.vuex_user_id,
        page: this.page,
      };
      this.$api.getNewsList(data).then((res) => {
        // console.log(res);
        this.newsList = [...this.newsList, ...res];
      });
    },
    // 跳转详情
    linkDetail(data) {
      let url =
        data.is_lvs == 1
          ? `/pages/subpackages/detail/lawyer?id=${data.id}`
          : `/pages/subpackages/detail/user?id=${data.id}`;
      uni.navigateTo({
        url,
      });
    },
    // 链接
    navLink(item) {
      this.$api
        .updateNews({
          id: item.ccid,
        })
        .then((res) => {
          // console.log(res);
        });
      let url = "";
      if (item.type == 1) {
        url = `/pages/subpackages/demand/detail?id=${item.xinxi_id}&type=${item.demand_release_type_id}&title=${item.title}`;
      } else if (item.type == 2) {
        url = `/pages/subpackages/topic/detail/detail?id=${item.xinxi_id}&content=${item.title}`;
      } else if (item.type == 3) {
        url = `/pages/subpackages/classify/inquire/detail?id=${item.xinxi_id}`;
      } else if (item.type == 4) {
        url = `/pages/subpackages/mine/partake/demand?id=${item.xinxi_id}`;
      } else if (item.type == 5) {
        url = `/pages/subpackages/mine/authen/index`;
      } else if (item.type == 6) {
        url = `/pages/subpackages/mine/bidding/index?type=1`;
      } else if (item.type == 7) {
        url = `/pages/subpackages/mine/bidding/index`;
      } else if (item.type == 8) {
        url = `/pages/subpackages/mine/order/order?type=1`;
      } else if (item.type == 9) {
        url = `/pages/subpackages/mine/authen/index`;
      } else if (item.type == 10) {
        url = `/pages/subpackages/mine/order/order?type=3`;
      } else if (item.type == 11) {
        this.qrCode = item.image;
        this.popupShow = true;
      }
      uni.navigateTo({ url });
    },
    imgtap(data, res) {
      data.ignore();
      this.toRoom(res);
    },
    //聊天的节点加上外层的div
    nodesFliter(str) {
      let nodeStr =
        '<div style="align-items: center;word-wrap:break-word;">' +
        str +
        "</div>";
      return nodeStr;
    },
    //获取消息列表
    getConversationList() {
      // 拉取会话列表
      let promise = this.tim.getConversationList();
      promise
        .then((res) => {
          let conversationList = res.data.conversationList; // 会话列表，用该列表覆盖原有的会话列表
          console.log(conversationList, "这是用户资料");
          if (conversationList.length) {
            //将返回的会话列表拼接上 用户的基本资料
            //说明：如果已经将用户信息 提交到tim服务端了 就不需要再次拼接
            this.$store.commit("updateConversationList", conversationList);
          }
        })
        .catch((err) => {
          console.warn("getConversationList error:", err); // 获取会话列表失败的相关信息
        });
    },
    //根据消息列表请求聊天对象的用户信息 并完成数据拼接
    getUserInfo(conversationList) {
      this.userAddConversationList = [];
      conversationList.forEach((item) => {
        let obj = {};
        obj.conversation = item;
        obj.user = {
          user: item.userProfile.nick,
          img: item.userProfile.avatar,
        };
        this.userAddConversationList.push(JSON.parse(JSON.stringify(obj)));
      });
    },
    toRoom(item) {
      this.$store.commit("updateConversationActive", item);
      uni.navigateTo({
        url: "/pages/news/room",
      });
    },
  },
  onReachBottom() {
    if (this.page * this.pagesize > this.newsList.length)
      return (this.status = "nomore");
    this.status = "loading";
    this.page = ++this.page;
    setTimeout(() => {
      this.getNewsList();
      if (this.page * this.pagesize > this.newsList.length)
        this.status = "nomore";
      else this.status = "loading";
    }, 500);
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },
};
</script>

<style lang="scss" scoped>
.news {
  min-height: 100vh;
  /* #ifdef H5 */
  min-height: calc(100vh - 94px);
  /* #endif */
  background-color: $uni-bg-color-grey;

  &-tab {
    background-color: $uni-bg-color;
    line-height: 80rpx;

    .item {
      &.active {
        position: relative;
        color: $uni-text-color-main;

        &::before {
          content: "";
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 60rpx;
          height: 2px;
          background-color: $uni-bg-color-main;
        }
      }
    }
  }

  &-list {
    .item {
      background-color: $uni-bg-color;
      border-radius: 10rpx;

      &:nth-child(n + 2) {
        margin: 20rpx 0 0;
      }

      .content {
        margin: 10rpx 0;

        &.active {
          color: $uni-text-color-main-red;
        }
      }

      .time {
        color: $uni-text-color-grey;
      }
    }
  }

  &-tim {
    .item {
      background-color: $uni-bg-color;
      border-radius: 10rpx;

      &:nth-child(n + 2) {
        margin: 20rpx 0 0;
      }
    }

    .info {
      min-height: 100rpx;
    }

    .msg {
      width: 40rpx;
      height: 40rpx;
      line-height: 40rpx;
      background-color: $uni-bg-color-main-red;
      border-radius: 50%;
      font-size: 24rpx;
      color: $uni-text-color-inverse;
      text-align: center;
    }
  }
}
</style>
